package baidu.bms.provider;

import baidu.bms.DemoServiceConsumer;
import baidu.bms.DemoServiceProvider;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sunqiyuan
 * @Classname DefaultDemoService
 * @Description TODO
 * @Date 2020/10/13 8:55 下午
 * @Version V1.0
 */
@DubboService(version = "${demo.service.version}")

public class DefaultDemoServiceProvider implements DemoServiceProvider {
    AtomicInteger count = new AtomicInteger(0);

    /**
     * The default value of ${dubbo.application.name} is ${spring.application.name}
     */
    @Value("${dubbo.application.name}")
    private String serviceName;


    //  @DubboReference(version = "${demo.service.version}",services = "annotation-provider")
    // check 不在boot启动时检查，该接口是否启动， lazy 懒加载
    @DubboReference(version = "${demo.service.version}", check = false, lazy = true)
    private DemoServiceConsumer demoServiceConsumer;


    @Override
    public String methodA(String name) {


        if (count.getAndAdd(1) % 2 == 0) {
            // dubbo call http
            String param = String.format(" %s ---> [%s : methodA: dubboServer > httpClient] ", name, serviceName);
            RestTemplate call = new RestTemplate();
            return call.getForObject("http://localhost:8081/methodB?name=" + param, String.class);

        } else {
            // dubbo call dubbo
            String param = String.format(" %s ---> [%s : methodA: dubboServer > dubboClient] ", name, serviceName);
            return demoServiceConsumer.methodB(param);
        }


    }
}
